var express = require('express');
var router = express.Router();
const Util = require('../note/Util');
const db = require('../note/db');
// 注册

// 定义当前路由主页
router.get('/', function(req, res) {
   res.render('register', { title: 'register', data:{msg:'hello node!',content:'我只想说一句MMP',uname:'suoge'} });
});
router.post('/',function(req,res){
  let name = req.body.name;
  let pass = Util.jiami(req.body.password);
  console.log('注册参数为：'+JSON.stringify(req.body));
  try {
    db.user.findAndCountAll({
      where:{
        username:name
      }
    }).then(ret=>{
      if(ret.count>0){
        console.log(ret);
        return  res.json({ret_code: 1, ret_msg: '该用户名已被注册'});
      }else{
        try {
          db.user.create({ username: name, password: pass, nick:name }).then(user => {
            console.log(user);
            return  res.json({ret_code: 0, ret_msg: '注册成功'});
          })

        } catch (e) {
          console.log(e);
          res.json({ret_code: 1, ret_msg: '注册失败'});
        }
      }
    })


  } catch (e) {
    console.log(err);
    res.json({ret_code: 1, ret_msg: '网络错误'});
  }

})

module.exports = router;
